import { H3Event } from 'h3'
import 'dotenv/config';
import z from 'zod'
import jwt from 'jsonwebtoken';

import { postUserLoginByAccount, getUserPersonInfo } from '~/service/yapi';

// const refreshTokens: Record<number, Record<string, any>> = {}
export const SECRET = process.env.JWT_SECRET 
console.log("%c Line:10 🍤 SECRET", "color:#f5ce50", SECRET);
export default eventHandler(async (event: any) => {
  let body = await readBody(event)
  try {
    let res: any = await postUserLoginByAccount({
      username: body.username,
      password: body.password
    })
    if (res.code != 1000) {
      if (res.code == 20003) {

        throw createError({ statusCode: 401, statusMessage: 'Unauthorized, 用户被封禁' })

      }

      throw createError({ statusCode: 403, statusMessage: 'Unauthorized, code !=1000' })

    } else {
      const { accessToken, refreshToken, expire, refreshExpire, userInfo } = res.data
      let userRes: any = await getUserPersonInfo({}, accessToken)
      let expiresIn = 30 * 24 * 60 * 60;
      const nuxtAccessToken = jwt.sign({ ...userRes.data, scope: ['user'] }, SECRET, { expiresIn })
      return {
        token: {
          accessToken,
          nuxtAccessToken,
          refreshToken,
          expire,
          refreshExpire
        }
      }
    }
  } catch (error:any) {
    if (error.statusCode == 401) {
      throw error
    }
    throw createError({ statusCode: 403, statusMessage: 'Unauthorized, httpStatus' })
  }

})
